import React from 'react';
import {withRouter, Link} from 'react-router-dom';
import {
  Form,
  Input,
  Button,
  Icon,
  Row,
  Col,
  message,
  Checkbox,
  Modal,
} from 'antd';
import {registerApi} from '@/api/auth';
// 背景
import LoginBg from '../LoginBg/LoginBg';
// 校验库
import {
  validatorUserName,
  validatorPassword,
  validatorPhone,
  validatorCode,
  hasErrors,
} from '@/common/Validator';

import prefixSelector from '../Common/prefixSelector';


const FormItem = Form.Item;

@withRouter
class RegisterForm extends React.Component {
  timerID = null; //定时器
  state= {
    sendSecondLast: 0,//重新发送验证码时间
    isSendedOnce: false, // 已经发送过一次了
    serviceBookVisible: false,//服务条款显示
    buttonLoading: false, // 按钮加载中
    sendLoading: false, // 发送验证码中
  }
  handleSubmit = e => {
    e.preventDefault ();
    const self = this;
    
    this.props.form.validateFields ((err, values) => {
      if (!err) {
        console.log ('Received values of form: ', values);

        if (!values.readed) {
          return message.error ('请先同意服务条款');
        }
        if (this.state.buttonLoading){
          return;
        }
        self.setState({
          buttonLoading: true
        });
        registerApi (values)
          .then (result => {
            console.log ('result', result);
          })
          .catch (() => {
            self.setState({
              buttonLoading: false
            });
            message.error ('系统繁忙，请稍后重试！');
          });
      }
    });
  };
  // 发送验证码
  sendCodeClick = () => {
    this.setState({
      sendSecondLast: 60
    });
    this.timerID = setInterval (() => {
      this.setState({
        sendSecondLast: this.state.sendSecondLast - 1
      });
      if (this.state.sendSecondLast === 0) {
        clearInterval (this.timerID);
        this.setState({
          isSendedOnce: true
        });
      }
    }, 1000);
  };
  // 打开服务条款
  showServiceBook = e => {
    e.preventDefault ();
    this.setState({
      serviceBookVisible: true
    });
  };
  // 关闭
  closeServiceBook = () => {
    this.setState({
      serviceBookVisible: false
    });
  };
  componentDidMount () {
    this.props.form.validateFields ();
  }
  componentWillUnmount () {
    clearInterval (this.timerID);
  }
  render () {
    // const self = this;
    const {sendSecondLast, isSendedOnce, buttonLoading, sendLoading} = this.state;
    // console.log(this.props.location);
    const {
      getFieldDecorator,
      getFieldError,
      isFieldTouched,
      getFieldsError,
    } = this.props.form;

    
    const phoneError = isFieldTouched ('phone') && getFieldError ('phone');
    const passwordError =
      isFieldTouched ('password') && getFieldError ('password');
    const codeError = isFieldTouched ('code') && getFieldError ('code');
    return (
      <div className="page-register">
        <div className="login-wrapper ">
          <Form
            onSubmit={this.handleSubmit}
            className="login-form register"
            ref={el => (this.$form = el)}
          >
            <h3>欢迎注册蒲公英投放系统</h3>
            <FormItem>
              {getFieldDecorator ('username', {
                rules: [
                  {
                    // { required: true, message: '请输入公司名称!' },
                    validator: validatorUserName,
                  },
                ],
              }) (
                <Input
                  prefix={
                    <Icon type="home" style={{color: 'rgba(0,0,0,.25)'}} />
                  }
                  placeholder="公司名称"
                />
              )}
            </FormItem>
            <FormItem
              validateStatus={passwordError ? 'error' : ''}
              help={passwordError || ''}
            >
              {getFieldDecorator ('password', {
                rules: [
                  {
                    required: true,
                    message: '请输入密码!',
                  },
                  {
                    validator: validatorPassword,
                  },
                ],
              }) (
                <Input
                  prefix={
                    <Icon type="lock" style={{color: 'rgba(0,0,0,.25)'}} />
                  }
                  type="password"
                  placeholder="密码"
                />
              )}
            </FormItem>
            <FormItem
              validateStatus={phoneError ? 'error' : ''}
              help={phoneError || ''}
            >
              {getFieldDecorator ('phone', {
                rules: [
                  {
                    required: true,
                    message: '请输入手机号码!',
                  },
                  {
                    validator: validatorPhone,
                  },
                ],
              }) (
                <Input
                  addonBefore={prefixSelector (getFieldDecorator)}
                  style={{
                    width: '100%',
                  }}
                />
              )}
            </FormItem>
            <FormItem
              validateStatus={codeError ? 'error' : ''}
              help={codeError || ''}
            >
              <Row gutter={8}>
                <Col span={8}>
                  {getFieldDecorator ('code', {
                    rules: [
                      {
                        required: true,
                        message: '请输入验证码!',
                      },
                      {
                        validator: validatorCode,
                      },
                    ],
                  }) (<Input />)}
                </Col>
                <Col span={16}>
                  <Button
                    className="login-form-button"
                    type="primary"
                    onClick={this.sendCodeClick}
                    loading={sendLoading}
                    disabled={
                      getFieldError ('phone') || sendSecondLast > 0
                        ? true
                        : false
                    }
                  >
                    {sendSecondLast > 0
                      ? `${sendSecondLast}s后重新发送`
                      : isSendedOnce ? '再次发送' : '发送短信验证码'}
                  </Button>
                </Col>
              </Row>
            </FormItem>
            <FormItem className="login-form-center">

              <Button
                type="primary"
                disabled={hasErrors (getFieldsError ())}
                htmlType="submit"
                className="login-form-button"
                loading={buttonLoading}
              >
                立即注册{hasErrors (getFieldsError ())}
              </Button>
              {getFieldDecorator ('readed', {
                valuePropName: 'checked',
                initialValue: true,
              }) (<Checkbox>我已阅读并同意相关服务条款和隐私政策</Checkbox>)}
              <p>
                <a href="" onClick={this.showServiceBook} className="fl">
                  服务条款
                </a>
                <Link className="fr" to={{pathname: '/login'}}>已有账号</Link>
              </p>
            </FormItem>
          </Form>
        </div>
        {/* canvas背景 */}
        <LoginBg />
        {/* 服务条款 */}
        <Modal
          wrapClassName="vertical-center-modal"
          visible={this.serviceBookVisible}
          footer={null}
          onCancel={this.closeServiceBook}
        >
          <div>
            <h4>服务条款</h4>
            <p>ddddd</p>
            <p>ddddd</p>
            <p>ddddd</p>
            <p>ddddd</p>
            <p>ddddd</p>
            <p>ddddd</p>
            <p>ddddd</p>
            <p>ddddd</p>
            <p>ddddd</p>
            <p>ddddd</p>
            <p>ddddd</p>
            <p>ddddd</p>
          </div>
        </Modal>
      </div>
    );
  }
}

export default Form.create () (RegisterForm);
